package register.utils;

/**
 * 验证邮箱格式的工具包
 *
 * */
public class EmailUtils {

    private static final String EMAIL_LIMIT_1 = "@";
    private static final String EMAIL_LIMIT_2 = "[.]";

    private String email;//邮箱


    /**
     * @param email 需要验证的邮箱
     * @apiNote 邮箱验证的构造函数
     * */
    public EmailUtils(String email) {
        this.email = email;
    }

    /**
     * @return 返回邮箱格式是否正确，正确为true，格式错误为false
     *
     * */
    public boolean isNormalize() {
        if(!find(email,'@')) return false;//如果存在多个“@”则返回false

        if(!find(email,'.')) return false;//如果存在多个“.”则返回false


        String[] arr1 = email.split(EMAIL_LIMIT_1);
        if(arr1[0].indexOf(".") != -1) {//如果“.”在“@”前面，则返回false
            return false;
        }
        if(arr1[0] == null || arr1[0].length() < 1) {//如果邮箱“@”前字符串长度小于1则返回false
            return false;
        }

        String[] arr2 = arr1[1].split(EMAIL_LIMIT_2);
        String str1 = arr1[0];
        String str2 = arr2[0];
        String str3 = arr2[1];
        if(str2 == null || str2.length() < 1) return false;
        if(str3 == null || str3.length() > 4 || str3.length() < 2) return false;//如果‘.’后面的字符串长度不为2-4区间，则返回false
        if(isNormalize2(str1) && isNormalize2(str2) && isNormalize2(str3)) {//验证字符串
            return true;
        }else {
            return false;
        }
    }

    private boolean find(String str,char ch) {
        int account = 0;
        int index = str.indexOf(ch);
        if(index == -1) return false;//如果不存在ch,则返回false
        while(true) {
            account++;
            index = str.indexOf(ch,index + 1);
            if(index == -1) break;
            if(account > 1) {//如果存在多个@，则返回false
                return false;
            }
        }
        return true;

    }

    /*
     * 验证字符串中的字符是否为字母或者数字
     *
     * */
    private boolean isNormalize2(String str) {

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if(ch >= 'a' && ch <= 'z') {
                continue;
            }else if(ch >= 'A' && ch <= 'Z') {
                continue;
            }else if(ch >= '0' && ch <= '9') {
                continue;
            }else {
                return false;
            }
        }
        return true;
    }


    /**
     * @param email 需要验证的邮箱
     * @return 返回邮箱格式是否正确，正确为true，错误为false
     * */
    public static boolean validate(String email) {

        String str = "([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4})";
        if(!email.matches(str)) {
            return false;
        }
        return true;

    }

}